package com.springboot.job.controller;

import com.springboot.job.schedule.JobVo;
import com.springboot.job.schedule.TaskRegister;
import com.springboot.job.schedule.TaskRunnable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
//@RequestMapping("job")
public class JobController {


    private HashMap<String, TaskRunnable> jobs = new HashMap<>();

    @Autowired
    private TaskRegister taskRegister;

    @GetMapping
    public ResponseEntity<String> hello(){
        return ResponseEntity.ok("success");
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public String addJob(@RequestBody JobVo jobVo){

        var task = new TaskRunnable(jobVo.getBeanName(), jobVo.getMethodName(), jobVo.getParams());

        taskRegister.addCronTask(task, jobVo.getCornExpression());

        jobs.put(jobVo.getJobName(), task);

        return "SUCCESS";
    }

    @DeleteMapping
    public String deleteJob(String jobName){

        if (!jobs.containsKey(jobName)) {
            return "ERROR";
        }

        taskRegister.removeCronTask(jobs.get(jobName));

        return "SUCCESS";
    }

}
